package com.enhe.gck.utils;

import cn.hutool.core.date.DatePattern;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;

public class DateUtil {

    // yyyy-MM-dd HH:mm:ss
    private static final DateTimeFormatter FORMATTER_NORM_DATETIME_PATTERN = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);
    public static final DateTimeFormatter TimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

    /**
     * Date转LocalDateTime
     */
    public static LocalDateTime dateToLocalDateTime(Date date) {
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * LocalDateTime转Date
     */
    public static Date localDateTimeToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * Date转String[yyyy-MM-dd HH:mm:ss]
     */
    public static String dateToString(Date date) {
        if (date == null) {
            return null;
        }
        return dateToLocalDateTime(date).format(FORMATTER_NORM_DATETIME_PATTERN);
    }

    public static LocalDateTime strToLocalDateTime(String loadStartTimeStr) {
        return LocalDateTime.parse(loadStartTimeStr, FORMATTER_NORM_DATETIME_PATTERN);
    }

    public static String DateTimeToString(LocalDateTime localDateTime) {
        if (Objects.isNull(localDateTime)) {
            return null;
        }
        return localDateTime.format(FORMATTER_NORM_DATETIME_PATTERN);
    }

    /**
     * 判断当前时间是否在指定时间段内（包头不包尾）
     *
     * @param nowTime   当前时间
     * @param timeFrame 时间段（格式：07:00~15:00）
     * @return 是否在时间范围内
     */
    public static boolean withinTheTimeFrame(LocalTime nowTime, String timeFrame) {
        String[] timeFrameArr = timeFrame.split("~");
        LocalTime startTime = LocalTime.parse(timeFrameArr[0] + ":00", TimeFormatter);
        LocalTime endTime = LocalTime.parse(timeFrameArr[1] + ":00", TimeFormatter);
        if (startTime.isAfter(endTime)) {
            return (nowTime.isAfter(startTime) || nowTime.equals(startTime)) || nowTime.isBefore(endTime);
        }
        return (nowTime.isAfter(startTime) || nowTime.equals(startTime)) && nowTime.isBefore(endTime);
    }
}
